/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Ui;

import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Font;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.regex.PatternSyntaxException;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.ListSelectionModel;
import javax.swing.RowFilter;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

/**
 *
 * @author Esteban
 */
public class PanelAsignarClasePaso2 extends javax.swing.JPanel {

    /**
     * Creates new form PanelAsignarClasePaso2
     */
    public PanelAsignarClasePaso2(JPanel panelCards, CardLayout cards) {
        this.cards=cards;
        this.panelCards=panelCards;
        initComponents();
        initComponents2();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        estudiante = new javax.swing.JLabel();
        campoBusquedaEst = new javax.swing.JTextField();
        btnSiguiente = new javax.swing.JButton();
        clase = new javax.swing.JLabel();
        scrollEstudiante = new javax.swing.JScrollPane();
        tablaEstudiante = new javax.swing.JTable();
        btnAnterior = new javax.swing.JButton();
        curso = new javax.swing.JLabel();
        campoCurso = new javax.swing.JLabel();
        horario = new javax.swing.JLabel();

        estudiante.setFont(new java.awt.Font("Calibri", 0, 18)); // NOI18N
        estudiante.setText("Buscar estudiante:");

        campoBusquedaEst.setFont(new java.awt.Font("Calibri", 0, 16)); // NOI18N
        campoBusquedaEst.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                campoBusquedaEstKeyReleased(evt);
            }
        });

        btnSiguiente.setFont(new java.awt.Font("Calibri", 0, 14)); // NOI18N
        btnSiguiente.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Img/siguiente.png"))); // NOI18N
        btnSiguiente.setText("Siguiente");
        btnSiguiente.setToolTipText("Siguiente paso");
        btnSiguiente.setEnabled(false);
        btnSiguiente.setHorizontalTextPosition(javax.swing.SwingConstants.LEFT);
        btnSiguiente.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                btnSiguienteMousePressed(evt);
            }
        });

        clase.setFont(new java.awt.Font("Calibri", 1, 20)); // NOI18N
        clase.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Img/asignar.png"))); // NOI18N
        clase.setText("Asignar Estudiante a Clase Compartida");

        scrollEstudiante.setBackground(new java.awt.Color(255, 255, 255));
        scrollEstudiante.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.LineBorder(new java.awt.Color(153, 153, 153), 1, true), "Paso 2. Seleccione el estudiante:", javax.swing.border.TitledBorder.LEFT, javax.swing.border.TitledBorder.TOP, new java.awt.Font("Calibri", 1, 18), new java.awt.Color(0, 153, 254))); // NOI18N

        tablaEstudiante.setFont(new java.awt.Font("Calibri", 0, 14)); // NOI18N
        tablaEstudiante.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Cédula", "Nombre completo"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tablaEstudiante.setGridColor(new java.awt.Color(0, 102, 204));
        tablaEstudiante.getTableHeader().setReorderingAllowed(false);
        scrollEstudiante.setViewportView(tablaEstudiante);

        btnAnterior.setFont(new java.awt.Font("Calibri", 0, 14)); // NOI18N
        btnAnterior.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Img/anterior.png"))); // NOI18N
        btnAnterior.setText("Anterior");
        btnAnterior.setToolTipText("Paso anterior");
        btnAnterior.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                btnAnteriorMousePressed(evt);
            }
        });

        curso.setFont(new java.awt.Font("Calibri", 0, 14)); // NOI18N
        curso.setText("Curso seleccionado:");

        campoCurso.setFont(new java.awt.Font("Calibri", 0, 14)); // NOI18N

        horario.setFont(new java.awt.Font("Calibri", 0, 14)); // NOI18N
        horario.setText("Horario seleccionado:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(224, 224, 224)
                .addComponent(clase)
                .addGap(0, 0, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(105, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(btnAnterior)
                        .addGap(18, 18, 18)
                        .addComponent(btnSiguiente)
                        .addGap(270, 270, 270))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(estudiante)
                        .addGap(43, 43, 43)
                        .addComponent(campoBusquedaEst, javax.swing.GroupLayout.PREFERRED_SIZE, 303, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(166, 166, 166))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(scrollEstudiante, javax.swing.GroupLayout.PREFERRED_SIZE, 628, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(93, 93, 93))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(horario)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(curso)
                                .addGap(18, 18, 18)
                                .addComponent(campoCurso, javax.swing.GroupLayout.PREFERRED_SIZE, 303, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(148, 148, 148))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(49, 49, 49)
                .addComponent(clase)
                .addGap(21, 21, 21)
                .addComponent(horario)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(campoCurso, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(curso))
                .addGap(40, 40, 40)
                .addComponent(scrollEstudiante, javax.swing.GroupLayout.PREFERRED_SIZE, 235, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(campoBusquedaEst, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(estudiante))
                .addGap(51, 51, 51)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnSiguiente)
                    .addComponent(btnAnterior))
                .addContainerGap(66, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void campoBusquedaEstKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_campoBusquedaEstKeyReleased
        // TODO add your handling code here:
        busquedaCurso();
    }//GEN-LAST:event_campoBusquedaEstKeyReleased

    private void btnSiguienteMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnSiguienteMousePressed
        // TODO add your handling code here:
        siguiente();
    }//GEN-LAST:event_btnSiguienteMousePressed

    private void btnAnteriorMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnAnteriorMousePressed
        // TODO add your handling code here:
        anterior();
    }//GEN-LAST:event_btnAnteriorMousePressed

    private void initComponents2(){
        tablaEstudiante.getTableHeader().setFont( new Font( "Calibri" , Font.PLAIN, 16 ));
        scrollEstudiante.getViewport().setBackground(Color.WHITE);
        
        ListSelectionModel listSelectionModel3 = tablaEstudiante.getSelectionModel();
        listSelectionModel3.addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent e) { 
                ListSelectionModel lsm = (ListSelectionModel)e.getSource();
                if(!lsm.isSelectionEmpty()){
                    habilitarNextPanel();
                }
                else{
                    deshabilitarNextPanel();
                }
            }
        });
        
        cargarEstudiantesActivos();
    }
    
    private void busquedaCurso(){
        TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(tablaEstudiante.getModel());
        tablaEstudiante.setRowSorter(sorter);
        if(campoBusquedaEst.getText().isEmpty()){
            sorter.setRowFilter(null);
        }    
        else{
            try{
                sorter.setRowFilter(RowFilter.regexFilter(campoBusquedaEst.getText()));
            }catch (PatternSyntaxException pse) {
                System.err.println("Bad regex pattern");
            }
        }
    }
    
    public void cargarEstudiantesActivos(){
        Connection conexion=null;
        Statement sentencia=null;
        ResultSet resultado=null;
        Object[][] estudiantes=null;
        
        try {
            Class.forName("org.postgresql.Driver");
        }catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        try{
            conexion = DriverManager.getConnection(cadenaConexion);
            sentencia = conexion.createStatement();
        
            String consultaSQL = "select cedula,nombre,apellido1,apellido2 from estudiante where activo='true'";
            resultado = sentencia.executeQuery(consultaSQL);
            int estudiantesSize=0;
            while(resultado.next()){
                estudiantesSize++;
            }
            
            if(estudiantesSize!=0){
                estudiantes=new Object[estudiantesSize][2];
                estudiantesSize=0;
                Statement sentencia2 = conexion.createStatement();
                ResultSet resultado2 = sentencia2.executeQuery(consultaSQL);
                String student;
                while (resultado2.next()) {
                    estudiantes[estudiantesSize][0]=resultado2.getString("cedula").replaceAll("\\s+","");
                    student=resultado2.getString("nombre").replaceAll("\\s+","")+" "+resultado2.getString("apellido1").replaceAll("\\s+","");  
                        if(resultado2.getString("apellido2")!=null){
                            student=student+" "+resultado2.getString("apellido2").replaceAll("\\s+",""); 
                        }
                    estudiantes[estudiantesSize][1]=student;   
                    estudiantesSize++;
                }
            }
                    
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "\n Imposible cargar los estudiantes \n Error en la base de datos", "Error", JOptionPane.ERROR_MESSAGE);
            e.printStackTrace();
            conexion = null;
        }
        finally {
            if (resultado != null) {
                try {
                    resultado.close();
                } catch (Exception e) {
                e.printStackTrace();
                }
            }
            if (sentencia != null) {
                try {
                    sentencia.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (conexion != null) {
                try {
                    conexion.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        
        tablaEstudiante.setModel(new javax.swing.table.DefaultTableModel(
            estudiantes,
                
            new String [] {
                "Cédula", "Nombre"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });  
        
        tablaEstudiante.getColumnModel().getColumn(0).setMaxWidth(95);
        tablaEstudiante.getColumnModel().getColumn(0).setMinWidth(95);
        
    }
    
    private void habilitarNextPanel(){
        btnSiguiente.setSelected(true);
        btnSiguiente.setEnabled(true);
    }
    
    private void deshabilitarNextPanel(){
        btnSiguiente.setSelected(false);
        btnSiguiente.setEnabled(false);
    }
    
    private void siguiente(){
        setOpcionesPaso3();
        cards.next(panelCards);
    }
    
    private void anterior(){
        cards.previous(panelCards);
    }
    
    public void setOpciones(String etqCurso, int codigo, String horario){
        setCurso(etqCurso);
        setCodigoCurso(codigo);
        setHorario(horario);
    }
    
    private void setCurso(String etqCurso){
        campoCurso.setText(etqCurso);
    }
    
    private void setCodigoCurso(int codigo){
        codigoCurso=codigo;
    }
    
    private void setHorario(String horario){
        this.horario.setText(horario);
    }
    
    public void setListaPaneles(ArrayList<JPanel> lista){
        paneles=lista;
    }
    
    private void setOpcionesPaso3(){
        ((PanelAsignarClasePaso3)paneles.get(2)).setOpciones(campoCurso.getText(),(String)tablaEstudiante.getValueAt(tablaEstudiante.getSelectedRow(), 1), codigoCurso, (String)tablaEstudiante.getValueAt(tablaEstudiante.getSelectedRow(), 0));
        ((PanelAsignarClasePaso3)paneles.get(2)).cargarClasesCompartidas();
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAnterior;
    private javax.swing.JButton btnSiguiente;
    private javax.swing.JTextField campoBusquedaEst;
    private javax.swing.JLabel campoCurso;
    private javax.swing.JLabel clase;
    private javax.swing.JLabel curso;
    private javax.swing.JLabel estudiante;
    private javax.swing.JLabel horario;
    private javax.swing.JScrollPane scrollEstudiante;
    private javax.swing.JTable tablaEstudiante;
    // End of variables declaration//GEN-END:variables
    private CardLayout cards;
    private JPanel panelCards;
    private static final String cadenaConexion = "jdbc:postgresql://localhost/SMAAMDB?" + "user=postgres&password=root";
    private ArrayList<JPanel> paneles;
    private int codigoCurso;
}
